import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'

import "@/assets/global.less"

axios.defaults.baseURL='http://big-event-vue-api-t.itheima.net'

import ElementUI from 'element-ui';   // +
// 引入ElementUI 样式    
import 'element-ui/lib/theme-chalk/index.css';  // +

//拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  const token = store.state.token
  if (token) {
    // 添加统一的headers
    config.headers.Authorization = token
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

//响应拦截器
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response;
}, function (error) {
  // 对响应错误做点什么
  // console.log(error);
  if(error.request.status==401){
    store.commit('updateToken','')
    router.push('/login')
  }
  return Promise.reject(error);
});


//路由守卫
//路由守卫
router.beforeEach((to,from,next)=>{
  // console.log(to,from,next);
  const token = store.state.token
  if(token){
    if(to.path==='/login'){
      next('/')
    }else{
      next()
    }
  }else{
    if (to.path ==='/reg'||to.path ==='/login') {
      next()
    }else{
      next('/login')
    }
  }
})
// 注册ElementUI 
Vue.use(ElementUI )  // +
Vue.prototype.$axios=axios

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
